package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;


public class AddItemToCartServlet extends HttpServlet {

    private String workingItemId;
    private Cart cart;

    private CatalogService catalogService =new CatalogService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        workingItemId = request.getParameter("workingItemId");
        Account account = (Account) request.getSession().getAttribute("account");
        HttpSession session = request.getSession();
        cart = (Cart)session.getAttribute("cart");
        if (account==null){
            request.getSession().setAttribute("login_msg","您尚未登录，请登录后再进行操作！");
            request.getRequestDispatcher("/WEB-INF/jsp/account/SignonForm.jsp").forward(request,response);
        }
        if (cart == null) {
            cart = new Cart();
        }
        LogService logService = new LogService();
        String loginmsg = "将"+workingItemId+"加入购物车";
        Date time = new Date();
        logService.insertLog_signin(account.getUsername(),loginmsg,time);
        if (cart.containsItemId(workingItemId)) {
            cart.incrementQuantityByItemId(workingItemId);
            catalogService.incrementQuantityByItemId(account.getUsername(),workingItemId);//持久化购物车
        } else {
            catalogService = new CatalogService();
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item, isInStock);
            catalogService.insertlongcart(account.getUsername(),workingItemId);//持久化购物车
        }
        session.setAttribute("cart", cart);
        response.sendRedirect(request.getContextPath()+"/longcart");
    }
}
